package com.yonghui.springsecurityoauth2demo.controller;

import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

/**
 * @author liyonghui
 * @description: TODO
 * @date 2021/12/5 13:50
 */
@RestController
@RequestMapping("/user")
public class UserController {
    /**
     * @description: 获取当前用户
     * @author liyonghui
     * @date 2021/12/5 13:52
     */
    @RequestMapping("getCurrentUser")
    public Object getCurrentUser(Authentication authentication) {
        return authentication.getPrincipal();
    }

    /**
     * @description: 解析JWT
     * @author liyonghui
     * @date 2021/12/5 16:18
     */
    @RequestMapping("getCurrentUser1")
    public Object getCurrentUser1(Authentication authentication, HttpServletRequest request) {
        String head = request.getHeader("Authorization");
        String token = head.substring(head.indexOf("bearer") + 7);
        return Jwts.parser().setSigningKey("test_key".getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token).getBody();
    }
}
